﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using HFK.DxFluentUI.DataProvider;
using HFK.DxFluentUI.LanguageModel.HorizontalGrid;

namespace HFK.DxFluentUI.HorizontalGrid.View
{
  public class DetailViewContext<ParentType, ComponentType> : ViewContext<ComponentType>, HorizontalGridDetailViewElement<ParentType, ComponentType>
    where ParentType : class
    where ComponentType : class
  {
    #region public members

    public HorizontalGridMainViewElement<ComponentType> BindToCollection(Func<ParentType, IList<ComponentType>> expression)
    {
      AddDataSource<ParentType, ComponentType>(ImplementingControl.Name, expression);
      return this;
    }

    #endregion

    #region internal members

    internal static DetailViewContext<ParentType, ComponentType> Create(HorizontalGridControlBase gridFactory, string caption, int viewLevel, ViewContext<ParentType> parentViewContext)
    {
      DetailViewContext<ParentType, ComponentType> result = new DetailViewContext<ParentType, ComponentType>(gridFactory, caption);
      result.ViewLevel = viewLevel;
      result.m_parentViewContext = parentViewContext;

      result.LevelNode = new DevExpress.XtraGrid.GridLevelNode();
      result.LevelNode.RelationName = result.ImplementingControl.Name;
      result.LevelNode.LevelTemplate = result.ImplementingControl;
      result.LevelNodeCollection = result.LevelNode.Nodes;
      parentViewContext.LevelNodeCollection.Add(result.LevelNode);

      return result;
    }

    internal void AddDataSource<A, R>(string key, Func<A, IList<R>> dataSource) where A : class
    {
      GridFactory.ImplementingControl.DataProvider.AddCall(key, dataSource);
      m_parentViewContext.ImplementingControl.RegisterRelatedView(key, GridFactory.ImplementingControl.DataProvider);
    }

    internal DevExpress.XtraGrid.GridLevelNode LevelNode { get; set; }

    #endregion

    #region private members

    ViewContext<ParentType> m_parentViewContext;

    private DetailViewContext(HorizontalGridControlBase grid, string caption)
      : base(grid, caption)
    {
    }

    #endregion
  }
}
